/**
 * Created by Administrator on 2017/10/17.
 */
public class LinearListImpl implements LinearList {
    private Node head;
    public  LinearListImpl()
    {
        head=new Node();
    }
    @Override
    public int length() {
        int count=0;
        Node p=head.getNext();
        while(p!=null)
        {
            count++;
            p=p.getNext();
        }
        return count;
    }

    @Override
    public int search(Object item) {
        Node p=head.getNext();
        while (p!=null)
        {
            p=p.getNext();
            return 1;
        }
        return -1;
    }

    @Override
    public Object getElement(int index) throws Exception {
        Node p=head.getNext();
        int k=0;
        while (p!=null||k<index)
        {
            k++;
           p= p.getNext();
        }
        if(p==null||index<0)
        {
            throw new Exception("链表中不存在第"+index+"个元素");
        }
        return p.getDaata();
    }

    @Override
    public Object remove(int index) throws Exception {
        return null;
    }
    //把item插入index位置
    @Override
    public void insert(int index, Object item) throws Exception {
        Node p=head;
        int k=-1;
        while (p!=null&&k<index)
        {
            p=p.getNext();
            k++;
        }
        if(index<0||(p==null&&k<index-1))
        {
            throw new Exception("插入位置非法");
        }
        else
        {
            Node s=new Node(item,null);
            p.setNext(s.getNext());
        }
    }

    @Override
    public boolean isEmpty() {
        Node p=head.getNext();
        if(p!=null)
        {
            return true;
        }
    else {
            return false;
        }
    }

    @Override
    public boolean isFull() {
        return false;
    }

    @Override
    public void clear() {

    }

    @Override
    public void display() {

    }
}
